package com.zjxf.resource;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.zjxf.base.common.OperationException;
import com.zjxf.resource.url.ResourceManagerUrlConstants;
import com.zjxf.utils.HttpClientUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

/**
 * created with IntelliJ IDEA
 *
 * @author: create by limu
 * Date: 2020/5/14
 * Time：9:22
 */
@Component
public class ResourceMangerUtils {

    public static final String IP_SERVER ="http://zjxf-a.qicp.vip/apis/remote/getResourceServiceIpAndPort";    //本机部署获取本机ip地址

    /**
     * 获取远程调用ip
     *
     * @return 返回值
     * @throws OperationException 自定义异常信息
     */
    public static String getRemoteIp() throws OperationException {
        String resultStr = HttpClientUtils.getInstance().httpGet(IP_SERVER, Maps.newHashMap());
        if (StringUtils.isNotBlank(resultStr)) {
            JSONObject resultObject = JSONObject.parseObject(resultStr);
            if (resultObject.getBoolean("success")) {
                return resultObject.getString("data");
            } else {
                return resultObject.getString("msg");
            }
        } else {
            throw new OperationException("获取ip服务异常");
        }
    }

    /**
     * 获取远程文件服务器地址以及ip
     * 示例: http://127.0.0.1:8085
     *
     * @return String
     * @throws OperationException 自定义异常
     */
    public static String getIpServerAndPort() throws OperationException {
        return getRemoteIp();
    }

    /**
     * md5转真实地址
     *
     * @param md5 文件md5
     * @return String
     * @throws OperationException 自定义异常现象
     */
    public static String changeRemoteUrl(String md5) throws OperationException {
        return getIpServerAndPort() + ResourceManagerUrlConstants.ONLINE_FILE + md5;
    }

    /**
     * 获取返回值的
     *
     * @param responseStr 返回参数
     * @return String
     * @throws OperationException 自定义异常信息
     */
    public static String getResourceFileId(String responseStr) throws OperationException {
        JSONObject responseJson = JSONObject.parseObject(responseStr);
        if (responseJson.getBoolean("success")) {
            return responseJson.getString("data");
        } else {
            throw new OperationException(responseJson.getString("msg"));
        }
    }

}
